#!/bin/sh
#
# sb2-session - interactive session management for scratchbox2
#
# This script can be used to save existing sessions even when
# sb2 was started without specifying '-S' -option.  This is
# usefull in cases where you have cloned target and installed
# some packages there and don't want it to go away when you
# exit sb2.
#
# Copyright (C) 2009 Mika Westerberg
# Licensed under GPL version 2
#
prog="$0"
progbase=`basename $0`
session_save_dir="$HOME/.scratchbox2/saved_sessions"

usage()
{
	cat <<EOF
Usage:	$progbase help
	$progbase save
	$progbase list
	$progbase delete SESSION
	$progbase attach [SESSION] [PARAMETERS]
	$progbase setenv VARIABLE VALUE
	$progbase showenv

Commands:
	help		shows this help
	save		saves current session
	list		lists detached sb2 sessions
	delete		deletes given session
	attach		attaches to saved sb2 session
	setenv		store a value for an environment variable
	showenv		show stored environment variables

This helper program can be used to create attachable scratchbox2 sessions.
You can save session even when you haven't done '-S session' during
sb2 startup.

Note that you can give parameters to 'attach' command which are passed
verbatim to sb2.  If there is only one session to attach, it is selected
automatically.

Basic usage is:

	[SB2 .. ] $ sb2-session save	# save session
	[SB2 .. ] $ ^D			# exit

later on we can then attach to this session:

	% sb2-session attach

if there are more than one saved sessions, then:

	% sb2-session list
	session.XXXX	TARGET_ARM	My Comment
	session.YYYY	TARGET_ARM	My Comment 2
	session.ZZZZ	TARGET_MIPS	
	% sb2-session attach session.YYYY

Here we pass '-eR' to sb2 and we only have one saved session:

	% sb2-session attach -- -eR

'--' is marks end of parameter list for sb2-session.


About environment variables:

"$progbase setenv VARIABLE VALUE" can be used to add environment variables,
that will become active when a saved session is later taken into use (either
by "sb2-session attach" or by "sb -J")

"$progbase setenv VARIABLE VALUE" does not change environment of sessions that
are already active.

"$progbase showenv" lists environment variable settings which have been stored
with this tool. It does not show environment variables from other sources.
EOF
	exit 1
}

write_session_info()
{
	session_descr="$1"
	session_info_file=$(mktemp -p $session_save_dir session.XXXXX)

	cat >> "$session_info_file" <<END
# SB2 SessionInfo:
# generated by sb2-session
SBOX_SESSION_DIR=$SBOX_SESSION_DIR
SBOX_SESSION_DESCRIPTION="$session_descr"
SBOX_TARGET=$sbox_target
END

	#
	# Make the session "joinable".  This keeps sb2
	# from removing the session directory. 
	#
	touch $SBOX_SESSION_DIR/.joinable-session
}

die()
{
	echo $1
	exit $2
}

attach_session()
{
	if [ "$#" -eq 0 ]; then
		session="--"
	else
		session="$1"
		shift
	fi

	if [ -z "$session" -o "$session" = "--" ]; then
		#
		# No session id given.  This means that there should
		# only be one session and we should use that.
		#
		count=$( ls $session_save_dir/session.* 2>/dev/null | wc -l )
		if [ "$count" -eq 1 ]; then
			session_file=$( ls $session_save_dir/session.* )
		elif [ "$count" -eq 0 ]; then
			die "No saved sessions available!" 1
		else
			die "You must specify session as parameter!" 1
		fi
	else
		session_file="$session_save_dir/$session"
		if [ ! -e "$session_file" ]; then
			die "Given session '$session' doesn't exist!" $?
		fi
	fi

	exec sb2 -J $session_file $*
}

save_session()
{
	echo -n "Session description: "
	read session_descr
	write_session_info "$session_descr"
}

list_sessions()
{
	for s in $( ls $session_save_dir/session.* 2>/dev/null ); do
		session_file=$(basename $s)
		session_descr=$( grep SBOX_SESSION_DESCRIPTION $s | \
		    sed 's/SBOX_SESSION_DESCRIPTION="\([^"]*\)"/\1/' )
		session_target=$( grep SBOX_TARGET $s | \
		    sed 's/SBOX_TARGET=\([^"]*\)/\1/' )
		printf "%s\t%s\t%s\n" "$session_file" "$session_target" \
		    "$session_descr"
	done
}

delete_session()
{
	session="$1"

	[ -z "$session" ] && usage
	if [ ! -e "$session_save_dir/$session" ]; then
		die "Given session '$session' doesn't exist!" $?
	fi

	sb2 -D "$session_save_dir/$session"
}

set_env_var()
{
	varname="$1"
	[ -z "$varname" ] && usage

	shift
	value="$*"

	if [ $inside_sb2 -eq 1 ]; then
		mkdir -p "$SBOX_SESSION_DIR/env_vars"
		echo "$varname=\"$value\"" >$SBOX_SESSION_DIR/env_vars/$varname
	else
		die "'sb2-session setenv' must be used inside existing session!" $?
	fi
}

show_env_vars()
{
	if [ $inside_sb2 -eq 1 ]; then
		count=$( ls $SBOX_SESSION_DIR/env_vars/* 2>/dev/null | wc -l )
		if [ "$count" -gt 0 ]; then
			cat $SBOX_SESSION_DIR/env_vars/*
		fi
	else
		die "'sb2-session showenv' must be used inside existing session!" $?
	fi
}

if [ $# -lt 1 ]; then
	usage
fi

command="$1"
shift

if [ ! -e "$session_save_dir" ]; then
	/bin/mkdir $session_save_dir 2>/dev/null ||
	    die "unable to create session save directory: $saved_sessions_dir" $rc
fi

if [ -z "$SBOX_SESSION_DIR" ]; then
	inside_sb2=0
else
	inside_sb2=1
fi

# validate that target binary really exists, otherwise sb2-show fails
case "$command" in
	help)
		usage
		;;
	attach)
		if [ $inside_sb2 -ne 0 ]; then
			echo -n "'attach' command cannot be run from inside "
			echo "sb2 session"
			exit 1
		fi
		attach_session $*
		;;

	save)
		#
		# Validate that we really are inside active sb2
		# session before.  Otherwise it is hard to save
		# it.
		#
		if [ $inside_sb2 -ne 1 ]; then
			echo -n "'save' command can only be run from inside "
			echo "sb2 session"
			exit 1
		fi

		. $SBOX_SESSION_DIR/sb2-session.conf

		save_session
		;;

	list)
		list_sessions
		;;

	delete)
		if [ $inside_sb2 -ne 0 ]; then
			echo -n "'delete' command cannot be run from inside "
			echo "sb2 session"
			exit 1
		fi

		delete_session "$1"
		;;

	setenv)
		set_env_var $*
		;;

	showenv)
		show_env_vars
		;;

	*)
		die "invalid command: $command" 1
esac
